﻿using BLL;
using Common;
using DevExpress.XtraEditors;
using DLL;
using gregn6Lib;
using NursingDocumentInfoSystem.Model;
using NursingFormSystem.Common;
using NursingFormSystem.Model;
using SQLDLL;
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace NursingDocumentInfoSystem
{
    public partial class NursingPrintXinXueGuan : XtraForm
    {
        protected string path = "";
        private GridppReport Report = new GridppReport();
        public static Tb_User LoginUser;
        public PatientInfoView PatientParams;
        public object printer;
        public string printdefaultsql = "";
        DateTime Start;
        DateTime End;
        string[] Patient;
        string[] id;
        DataTable IOData;
        DataTable BlankHeightData;
        ElectronicSignature es;
        float PageBlankHeight;//
        bool continueflag;
        int continuenum = 0;

        public NursingPrintXinXueGuan(string[] id, Tb_User loginUser, string[] patientInfo, DateTime StartDate, DateTime EndDate, bool continueflag, int descindex)
        {
            InitializeComponent();
            Start = StartDate;
            End = EndDate;
            LoginUser = loginUser;
            Patient = patientInfo;
            this.id = id;
            this.continueflag = continueflag;
            this.continuenum = descindex;
            es = new ElectronicSignature(LoginUser);
            string printdefaultsql = @"SELECT [PrinterName] FROM [BNNursingDocsSystem_Develop].[dbo].[PrintDefault](NOLOCK) where FromName  = '" + Kind.getFileName() + "' and MACAddress = '" + Kind.GetMacAddress() + "'";
            object printer = SqlHelper.ExecuteScalar(CommandType.Text, printdefaultsql);
            if (printer == null)  //没设置过打印机
            {
                XtraMessageBox.Show("此页面，该MAC地址未设置过默认打印机，请预览时设置默认打印机，系统将自动保存！");
            }
            else
            {
                Report.Printer.PrinterName = printer.ToString();
            }

            //设置 ShowPrintDlg 属性，让点击工具栏中的打印按钮时不显示打印对话框
            axGRPrintViewer1.ShowPrintDlg = false;
            try
            {
                if (File.Exists(System.Windows.Forms.Application.StartupPath + @"\GRFModel\Ydhl_GRF\NursingGrfXinXueGuan.grf"))
                {
                    Report.LoadFromFile(System.Windows.Forms.Application.StartupPath + @"\GRFModel\Ydhl_GRF\NursingGrfXinXueGuan.grf");
                }
                else
                {
                    Report.LoadFromFile(@"../../Ydhl_GRF/NursingGrfXinXueGuan.grf");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("加载临时医嘱表单失败，请检查文件Ydhl_GRF/NursingGrfXinXueGuan.grf是否存在");
                WriteLog.WriteLogString(ex.Message + ".  加载临时医嘱表单失败，请检查文件Ydhl_GRF/Order-LZ.grf是否存在");
            }
            if (continueflag)
            {
                GetBlankHeight();
                if ((BlankHeightData != null) && (BlankHeightData.Rows.Count > 0))
                {
                    float f = 29.7f - 2.5f - Convert.ToSingle(BlankHeightData.Rows[0]["BlackHeight"].ToString());
                    Report.ParameterByName("Parameter1").AsFloat = f;//此时应当是从获取对应的值
                }
            }

            Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord);
            Report.PageProcessRecord += Report_PageProcessRecord;
            axGRPrintViewer1.Report = Report;
            Report.PrintEnd += Report_PrintEnd;
            Report.GeneratePagesEnd += Report_GeneratePagesEnd;
            GetSumIO();
        }

        private void GetSumIO()
        {
            string sql = @"SELECT SumDate,Group12,Group24,GroupDiy,BeginTime FROM [BNNursingDocsSystem_Develop].[dbo].[NursingFormSumIO](NOLOCK) where PatientId ='{0}' AND VisitId='{1}' AND FormId='{2}' ORDER BY SumDate";
            sql = string.Format(sql, Patient[0], Patient[1], (int)FormType.TempbedNursingCVP);
            IOData = new DataTable();
            IOData = SqlHelper.ExecuteDataset(sql, CommandType.Text).Tables[0];
        }

        private void GetBlankHeight()
        {
            string sql = @"SELECT BlackHeight FROM [BNNursingDocsSystem_Develop].[dbo].[NursingContinuePrint](NOLOCK) where PatientId ='{0}' AND VisitId='{1}'  AND FormId='{2}'";
            sql = string.Format(sql, Patient[0], Patient[1], (int)FormType.TempbedNursingCVP);
            BlankHeightData = new DataTable();
            BlankHeightData = SqlHelper.ExecuteDataset(sql, CommandType.Text).Tables[0];
        }

        private void ReportFetchRecord()
        {
            string select = @"SELECT * FROM [BNNursingDocsSystem_Develop].[dbo].[t_ClinicalNursingXinXueGuan](NOLOCK) where 1 = 1  AND ";
            select += "Date between '" + Start.ToString("yyyy-MM-dd") + "' and '" + End.ToString("yyyy-MM-dd") + "'";
            select += string.Format(" AND ( PatientId = '{0}' AND VISIT_ID = {1} ) AND ( ", Patient[0], Patient[1]);
            if (id.Length == 1 && !string.IsNullOrEmpty(id[0]) && Regex.IsMatch(id[0], @"^\d+$"))
            {
                select += "Id ='" + id[0] + "'";
            }
            else
            {
                for (int i = 0; i < id.Length; i++)
                {
                    if (!string.IsNullOrEmpty(id[i]) && Regex.IsMatch(id[i], @"^\d+$"))
                        select += "Id ='" + id[i] + "'or ";
                }
                select = select.Substring(0, select.Length - 3);
            }
            select += ") order  by date desc , time desc";
            //select += ") order  by date asc , time asc";
            DataTable selectNursingForm = SqlHelper.ExecuteDataset(select, CommandType.Text).Tables[0];
            //如果有续打进行数据的处理；
            if ((selectNursingForm != null) && (continueflag))
            {
                for (int m = selectNursingForm.Rows.Count - 1; m > 0; m--)
                {
                    if (m > continuenum)
                    {
                        selectNursingForm.Rows.RemoveAt(m);
                    }
                }
            }

            //再进行升序
            selectNursingForm.DefaultView.Sort = "date ASC,time ASC";
            selectNursingForm = selectNursingForm.DefaultView.ToTable();

            DataTable dt = new DataTable();
            if (selectNursingForm != null)
            {
                CreateDataTableHead(dt);
                string valueof24 = "1980-01-01";//判断当天是否包含24小时统计量的值
                string valueof24_1 = "1980-01-01";//判断当天是否包含24小时统计量的值
                string valueofdiy = "1980-01-01";//判断当天是否包含diy小时统计量的值
                string valueofdiy_1 = "1980-01-01";//判断当天是否包含diy小时统计量的值
                for (int i = 0; i < selectNursingForm.Rows.Count; i++)
                {
                    ClinicalNursing cn = XmlUtil.XMLToObject<ClinicalNursing>(selectNursingForm.Rows[i]["data"] + "", Encoding.UTF8);
                    string newpageflag = "";
                    string group12 = "";
                    string group24 = "";
                    string groupdiy = "";
                    string riqisum = "";
                    string qianming;
                    string Vaule01 = "";
                    string Vaule02 = "";
                    string valueDiy01 = "";
                    string valueDiy02 = "";
                    string image1 = "";
                    string HoursDiy = "";
                    string TimeDiy = "00:00";
                    string RYHS = selectNursingForm.Rows[i]["NursName"] + "";
                    string date = Convert.ToDateTime(selectNursingForm.Rows[i]["Date"]).ToString("yyyy-MM-dd");
                    string time = selectNursingForm.Rows[i]["Time"] + "";
                    string id01 = selectNursingForm.Rows[i]["ID"] + "";
                    string PatientId = selectNursingForm.Rows[i]["PatientId"] + "";
                    string PatientName = selectNursingForm.Rows[i]["PatientName"] + "";
                    string bloodPressure = "";
                    string areaId = selectNursingForm.Rows[i]["AreaId"] + "";
                    qianming = selectNursingForm.Rows[i]["NursName"] + "";
                    if (selectNursingForm.Rows[i]["IsNewPageFlag"] != null)
                    {
                        newpageflag = selectNursingForm.Rows[i]["IsNewPageFlag"].ToString();
                    }
                    else
                    {
                        newpageflag = "";
                    }
                    riqisum = selectNursingForm.Rows[i]["Date"] + "";// 默认的初始值
                    //先给Group24的赋值
                    bool sumflag = true;//今日是否统计继续
                    if (valueof24_1.Contains(Convert.ToDateTime(date).ToString("yyyy-MM-dd")))
                    {
                        riqisum = Convert.ToDateTime(valueof24).ToString("yyyy-MM-dd");
                        string _strtime1 = "07:00";
                        TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                        TimeSpan dspnow = DateTime.Parse(time).TimeOfDay;
                        if (dspnow <= dsptime1)
                        {
                            group24 = valueof24 + " 00:00:00.024";
                            sumflag = false;
                        }
                    }
                    if (valueofdiy_1.Contains(Convert.ToDateTime(date).ToString("yyyy-MM-dd")))
                    {
                        object fullEndTime = null;//声明结束时间
                        riqisum = Convert.ToDateTime(valueofdiy).ToString("yyyy-MM-dd");//获取昨天的日期 即统计日期
                        DataRow row = IOData.Select(" sumdate = '" + riqisum + "'")[0];//获取统计日期对应的io表数据
                        object obj_stime = row["BeginTime"];//取得数据起始时间
                        object obj_groupdiy = row["GroupDiy"];//取得数据统计小时数
                        if (obj_stime == DBNull.Value) obj_stime = "07:00";
                        if (obj_groupdiy == DBNull.Value) obj_groupdiy = "0";                        
                        HoursDiy = obj_groupdiy.ToString();//grf字段赋值
                        //算出结束时间
                        fullEndTime = Convert.ToDateTime(riqisum + " " + obj_stime).AddHours(Convert.ToInt32(obj_groupdiy));
                        TimeDiy = Convert.ToDateTime(fullEndTime).AddMinutes(1).ToString("HH:mm");//结束时间字段赋值
                        //如果结束日期和起始日期不一致 判定为第二天 显示为第二天的日期
                        if (!Convert.ToDateTime(fullEndTime).ToString("yyyy-MM-dd").Equals(riqisum))
                            riqisum = Convert.ToDateTime(riqisum).AddDays(1).ToString("yyyy-MM-dd");
                        //算出完整起始时间
                        DateTime fullBeginTime = Convert.ToDateTime(valueofdiy + " " + obj_stime);
                        //算出完整护理时间
                        DateTime fullItemTime = Convert.ToDateTime(date + " " + time);
                        //完整护理时间介于起始时间和结束时间则显示统计标识组
                        if (fullItemTime >= fullBeginTime && fullItemTime <= Convert.ToDateTime(fullEndTime))
                        {
                            groupdiy = Convert.ToDateTime(fullEndTime).ToString("yyyy-MM-dd 00:00:00.001");
                            sumflag = false;
                        }
                    }
                    if (sumflag)
                    {
                        //根据统计的标识来加载赋值是否显示统计行
                        if (IOData.Rows.Count > 0)
                        {
                            for (int j = 0; j < IOData.Rows.Count; j++)
                            {
                                bool endflag = false;//统计标识
                                string tempdate = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd");
                                if (tempdate.Contains(date))//相同的日期
                                {
                                    //12小时的 Y判断
                                    if ((IOData.Rows[j]["Group12"] + "").Contains("Y"))
                                    {
                                        riqisum = date;
                                        string _strtime1 = "07:01";
                                        string _strtime2 = "19:00";
                                        TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;
                                        TimeSpan dsptime2 = DateTime.Parse(_strtime2).TimeOfDay;
                                        TimeSpan dspnow = DateTime.Parse(time).TimeOfDay;
                                        if ((dspnow >= dsptime1) && (dspnow <= dsptime2))
                                        {
                                            group12 = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd HH:mm:ss") + ".012";
                                            endflag = true;
                                        }
                                    }

                                    //24小时的 Y判断
                                    if ((IOData.Rows[j]["Group24"] + "").Contains("Y"))
                                    {
                                        riqisum = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                                        string _strtime1 = "07:01";
                                        TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;//起始时间
                                        TimeSpan dspnow = DateTime.Parse(time).TimeOfDay;//护理时间
                                        if (dspnow >= dsptime1)
                                        {
                                            group24 = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd HH:mm:ss") + ".024";
                                            endflag = true;
                                        }
                                        //获取下一天的日期，并且赋值给参数，来判断24小时第二天的统计值
                                        DateTime tempdt01 = Convert.ToDateTime(date);
                                        valueof24 = Convert.ToDateTime(date).ToString("yyyy-MM-dd");
                                        valueof24_1 = tempdt01.AddDays(1).ToString("yyyy-MM-dd");
                                    }

                                    //自定义小时
                                    //报表 HoursDiy 字段赋值
                                    string tempHoursDiy = (IOData.Rows[j]["GroupDiy"] != DBNull.Value && IOData.Rows[j]["GroupDiy"] != null) ? (IOData.Rows[j]["GroupDiy"]).ToString() : "";
                                    if (!string.IsNullOrEmpty(tempHoursDiy) && Regex.IsMatch(tempHoursDiy, @"^\d+$") && Convert.ToInt32(tempHoursDiy) > 0)
                                    {
                                        //统计准备字段
                                        string tempDate = Convert.ToDateTime(IOData.Rows[j]["SumDate"]).ToString("yyyy-MM-dd");//统计日期
                                        string stime = (IOData.Rows[j]["BeginTime"] != DBNull.Value && IOData.Rows[j]["BeginTime"] != null) ? (IOData.Rows[j]["BeginTime"]).ToString() : "07:01";//获得开始时间
                                        DateTime etime = Convert.ToDateTime(tempDate + " " + stime).AddHours(Convert.ToInt32(tempHoursDiy));//算出结束时间
                                        //报表 TimeDiy 字段赋值
                                        TimeDiy = etime.AddMinutes(1).ToString("HH:mm");//自定义开始时间
                                        riqisum = tempDate;
                                        bool nextDay = false;
                                        if (!etime.ToString("yyyy-MM-dd").Equals(tempDate))
                                        {
                                            riqisum = Convert.ToDateTime(riqisum).AddDays(1).ToString("yyyy-MM-dd");
                                            nextDay = true;
                                        }
                                        string _strtime1 = stime;
                                        string _strtime2 = TimeDiy;
                                        TimeSpan dsptime1 = DateTime.Parse(_strtime1).TimeOfDay;//起始时间
                                        TimeSpan dspnow = DateTime.Parse(time).TimeOfDay;//护理时间

                                        DateTime fullstime = (Convert.ToDateTime(tempDate).AddHours(dsptime1.Hours)).AddMinutes(dsptime1.Minutes);//完整起始时间
                                        DateTime itemTime = Convert.ToDateTime(date).AddHours(dspnow.Hours).AddMinutes(dspnow.Minutes);//完整护理时间

                                        if ((itemTime >= fullstime) && itemTime <= etime)
                                        {
                                            groupdiy = etime.ToString("yyyy-MM-dd 00:00:00.001");
                                            HoursDiy = tempHoursDiy;
                                            endflag = true;
                                        }
                                        if (Convert.ToDateTime(tempDate).AddDays(1).ToString("yyyy-MM-dd") == etime.ToString("yyyy-MM-dd"))
                                        {
                                            //获取下一天的日期，并且赋值给参数，来判断diy小时第二天的统计值
                                            DateTime tempdt01 = Convert.ToDateTime(date);
                                            valueofdiy = date.ToString().Replace("-", "/");
                                            valueofdiy_1 = tempdt01.AddDays(1).ToString("yyyy-MM-dd");
                                        }
                                    }

                                    if (endflag)
                                    {
                                        break;
                                    }

                                }
                            }
                        }
                        else
                        {
                            group12 = "";
                            group24 = "";
                            groupdiy = "";
                        }
                    }
                    if (!string.IsNullOrEmpty(RYHS))
                    {
                        image1 = es.GetElectricSignBase64(areaId, qianming);
                    }
                    if (!Base.ESSwitch.Equals("on"))
                    {
                        qianming = selectNursingForm.Rows[i]["NursName"] + "";
                    }
                    else
                    {
                        qianming = image1;
                    }
                    //统计12 24小时的
                    float tempinput = 0;
                    if (cn.Intakevalue.Contains(","))
                    {
                        string[] str = cn.Intakevalue.Split(',');
                        for (int j = 0; j < str.Length; j++)
                        {
                            if (RegexHelper.IsFloat(str[j]))
                            {
                                tempinput = tempinput + Convert.ToSingle(str[j]);
                            }
                        }
                        Vaule01 = Convert.ToString(tempinput);
                    }
                    else
                    {
                        Vaule01 = cn.Intakevalue;
                    }

                    float tempout = 0;
                    if (cn.Dischargevalue.Contains(","))
                    {
                        string[] str = cn.Dischargevalue.Split(',');
                        for (int j = 0; j < str.Length; j++)
                        {
                            if (RegexHelper.IsFloat(str[j]))
                            {
                                tempout = tempout + Convert.ToSingle(str[j]);
                            }
                        }
                        Vaule02 = Convert.ToString(tempout);
                    }
                    else
                    {
                        Vaule02 = cn.Dischargevalue;
                    }

                    //统计自定义的
                    if (true)
                    {
                        float tempinputd = 0;
                        if (cn.Intakevalue.Contains(","))
                        {
                            string[] str = cn.Intakevalue.Split(',');
                            for (int j = 0; j < str.Length; j++)
                            {
                                if (RegexHelper.IsFloat(str[j]))
                                {
                                    tempinputd = tempinputd + Convert.ToSingle(str[j]);
                                }
                            }
                            valueDiy01 = Convert.ToString(tempinputd);
                        }
                        else
                        {
                            valueDiy01 = cn.Intakevalue;
                        }

                        float tempoutd = 0;
                        if (cn.Dischargevalue.Contains(","))
                        {
                            string[] str = cn.Dischargevalue.Split(',');
                            for (int j = 0; j < str.Length; j++)
                            {
                                if (RegexHelper.IsFloat(str[j]))
                                {
                                    tempoutd = tempoutd + Convert.ToSingle(str[j]);
                                }
                            }
                            valueDiy02 = Convert.ToString(tempoutd);
                        }
                        else
                        {
                            valueDiy02 = cn.Dischargevalue;
                        }
                    }

                    //当传入字符串为空值时，会影响Report.FieldByName("IsNewPageFlag")值获取的问题，具体原因未知，先给起赋值一个初值，不影响显示和判断
                    if (image1 == "")
                    {
                        image1 = "image";
                    }

                    #region 对入量的多个输入进行显示排序
                    if (cn.Intakename.Contains(",")) //有多个输入量名称
                    {
                        string[] tempintakename = cn.Intakename.Split(',');
                        string[] tempintakevalue = cn.Intakevalue.Split(',');
                        string[] tempintakediway = cn.Intakediway.Split(',');

                        cn.Intakename = ""; cn.Intakevalue = ""; cn.Intakediway = "";
                        for (int j = 0; j < tempintakename.Length; j++)
                        {
                            if (!string.IsNullOrEmpty(tempintakename[j]))
                            {
                                //报表中入量名称一行有10个字节
                                int rows1 = 0;//初始行数
                                int templength1 = Encoding.Default.GetByteCount(tempintakename[j]);
                                int Remainder1 = templength1 % 10;
                                if (Remainder1 == 0)
                                {
                                    rows1 = templength1 / 10;
                                }
                                else
                                {
                                    rows1 = (templength1 / 10) + 1;
                                }
                                //报表中入量值一行有4个字节
                                int rows2 = 0;//初始行数
                                int templength2 = 0;
                                if (j < tempintakevalue.Length)
                                {
                                    templength2 = Encoding.Default.GetByteCount(tempintakevalue[j]);
                                }
                                else
                                {
                                    templength2 = 0;
                                }
                                int Remainder2 = templength2 % 4;
                                if (Remainder2 == 0)
                                {
                                    rows2 = templength2 / 4;
                                }
                                else
                                {
                                    rows2 = (templength2 / 4) + 1;
                                }
                                //报表中入量途径一行有6个字节
                                int rows3 = 0;//初始行数
                                int templength3 = 0;
                                if (j < tempintakediway.Length)
                                {
                                    templength3 = Encoding.Default.GetByteCount(tempintakediway[j]);
                                }
                                else
                                {
                                    templength3 = 0;
                                }
                                int Remainder3 = templength3 % 6;
                                if (Remainder3 == 0)
                                {
                                    rows3 = templength3 / 6;
                                }
                                else
                                {
                                    rows3 = (templength3 / 6) + 1;
                                }

                                if (rows1 >= rows2)
                                {
                                    for (int m = 0; m < (rows1 - rows2); m++)
                                    {
                                        if (j < tempintakevalue.Length)
                                        {
                                            tempintakevalue[j] = tempintakevalue[j] + "\r\n";
                                        }
                                    }
                                }

                                if (rows1 >= rows3)
                                {
                                    for (int m = 0; m < (rows1 - rows3); m++)
                                    {
                                        if (j < tempintakediway.Length)
                                        {
                                            tempintakediway[j] = tempintakediway[j] + "\r\n";
                                        }
                                    }
                                }

                                cn.Intakename = cn.Intakename + tempintakename[j] + "\r\n\r\n";
                                if (rows2 > rows1)
                                {
                                    if (j < tempintakevalue.Length)
                                    {
                                        cn.Intakevalue = cn.Intakevalue + tempintakevalue[j] + "\r\n";
                                    }

                                }
                                else if (j < tempintakevalue.Length)
                                {
                                    cn.Intakevalue = cn.Intakevalue + tempintakevalue[j] + "\r\n\r\n";
                                }

                                if (rows3 > rows1)
                                {
                                    if (j < tempintakediway.Length)
                                    {
                                        cn.Intakediway = cn.Intakediway + tempintakediway[j] + "\r\n";
                                    }
                                }
                                else if (j < tempintakediway.Length)
                                {
                                    cn.Intakediway = cn.Intakediway + tempintakediway[j] + "\r\n\r\n";
                                }

                            }
                        }
                    }
                    #endregion

                    #region 对出量的多个输入进行显示排序
                    if (cn.Dischargename.Contains(",")) //有多个输入量名称
                    {
                        string[] tempdischargename = cn.Dischargename.Split(',');
                        string[] tempdischargevalue = cn.Dischargevalue.Split(',');

                        cn.Dischargename = ""; cn.Dischargevalue = "";
                        for (int j = 0; j < tempdischargename.Length; j++)
                        {
                            if (!string.IsNullOrEmpty(tempdischargename[j]))
                            {
                                //报表中出量名称一行有10个字节
                                int rows1 = 0;//初始行数
                                int templength1 = Encoding.Default.GetByteCount(tempdischargename[j]);
                                int Remainder1 = templength1 % 10;
                                if (Remainder1 == 0)
                                {
                                    rows1 = templength1 / 10;
                                }
                                else
                                {
                                    rows1 = (templength1 / 10) + 1;
                                }
                                //报表中出量值一行有4个字节
                                int rows2 = 0;//初始行数
                                int templength2 = Encoding.Default.GetByteCount(tempdischargevalue[j]);
                                int Remainder2 = templength2 % 4;
                                if (Remainder2 == 0)
                                {
                                    rows2 = templength2 / 4;
                                }
                                else
                                {
                                    rows2 = (templength2 / 4) + 1;
                                }

                                if (rows1 >= rows2)
                                {
                                    for (int m = 0; m < (rows1 - rows2); m++)
                                    {
                                        tempdischargevalue[j] = tempdischargevalue[j] + "\r\n";
                                    }
                                }

                                cn.Dischargename = cn.Dischargename + tempdischargename[j] + "\r\n\r\n";
                                if (rows2 > rows1)
                                {
                                    cn.Dischargevalue = cn.Dischargevalue + tempdischargevalue[j] + "\r\n";
                                }
                                else
                                {
                                    cn.Dischargevalue = cn.Dischargevalue + tempdischargevalue[j] + "\r\n\r\n";
                                }
                            }
                        }
                    }
                    #endregion

                    //高压cn.Systolicpressure
                    //低压cn.Diastolicpressure
                    if (cn != null)
                    {
                        if ((cn.Systolicpressure != "") || (cn.Diastolicpressure != ""))
                        {
                            bloodPressure = cn.Systolicpressure + "/" + cn.Diastolicpressure;
                        }
                        else
                        {
                            bloodPressure = "";
                        }

                        DataRow row = dt.NewRow();
                        row["DepartmentName"] = Patient[9];
                        row["DepartName"] = Patient[11];
                        row["Bed_No"] = Patient[5];
                        row["PatientName"] = Patient[2];
                        row["SEX"] = Patient[3];
                        row["PatientAge"] = Patient[4];
                        row["PatientID"] = Patient[0];
                        row["IN_DATE"] = Patient[6];
                        row["InTime"] = Patient[7];
                        row["Date"] = date;//日期
                        row["Time"] = time;//时间
                        row["temperature"] = cn.Temper;//体温
                        row["pulse"] = cn.Pulse;//脉搏
                        row["HeartRate"] = cn.HeartRate;//心率
                        row["breathing"] = cn.Breath;//呼吸
                        row["xueya"] = bloodPressure;//血压
                        row["Spo2"] = cn.Spo2;//血氧饱和度
                        row["StandUp"] = cn.StandUp;//翻身
                        row["CVP"] = cn.CVP;//CVP
                        row["Intakename"] = cn.Intakename;//输入名称
                        row["Intakevalue"] = cn.Intakevalue;//输入量
                        row["Intakediway"] = cn.Intakediway;//途径
                        row["Dischargename"] = cn.Dischargename.Replace(",", "\r\n\r\n");//排除名称
                        row["Dischargevalue"] = cn.Dischargevalue.Replace(",", "\r\n\r\n");//排除量
                        row["Tendcontent"] = StringHelpers.OutputDecode(cn.Tendcontent);//病情及护理措施
                        row["NursName"] = qianming;//签名
                        //row["ElectricSignBase64"] = image1;//电签;
                        row["IsNewPageFlag"] = newpageflag;//另起一页
                        row["Group12"] = group12;//分组统计标识12
                        row["Group24"] = !string.IsNullOrEmpty(group24) ? Convert.ToDateTime(group24).AddDays(1).ToString("yyyy-MM-dd") : "";//分组统计标识24
                        row["Vaule01"] = Vaule01;//合计入量
                        row["Vaule02"] = Vaule02;//合计出量
                        row["DateSum"] = riqisum;//统计行显示日期
                        row["HoursDiy"] = HoursDiy;//自定义统计的小时数-入
                        row["HoursDiyOut"] = HoursDiy;//自定义统计的小时数-出
                        row["TimeDiy"] = TimeDiy;//自定义统计的小时数后的时间相对于7:00
                        row["Groupdiy"] = groupdiy;//组标识
                        row["ValueDiy01"] = valueDiy01;//合计入量diy
                        row["ValueDiy02"] = valueDiy02;//合计出量diy
                        dt.Rows.Add(row);
                    }
                }
                dt.DefaultView.Sort = "date ASC,time ASC";
                DataTable data = dt.DefaultView.ToTable();
                Utility.FillRecordToReport(Report, data);
            }
        }

        //打印结束
        private void Report_PrintEnd()
        {
            //保存空白高度
            SetBlankHeight();
        }
        //打印结束
        private void Report_GeneratePagesEnd()
        {
            //得到空白高度
            PageBlankHeight = (float)Report.PageBlankHeight;
            //将参数赋值为空白页高度
        }

        //根据加载的值来判断是否另起一页
        private void Report_PageProcessRecord()
        {
            IGRField ob = Report.FieldByName("IsNewPageFlag");

            if ((ob != null) && (ob.Value != null))
            {
                if (ob.Value.ToString().Contains("Y"))
                {
                    Report.ForceNewPage();//强制另起一页
                }
            }

        }
        /// <summary>
        /// 加载列头
        /// </summary>
        /// <param name="dt"></param>
        private static void CreateDataTableHead(DataTable dt)
        {
            dt.Columns.Add("DepartmentName", typeof(string));
            dt.Columns.Add("DepartName", typeof(string));
            dt.Columns.Add("Bed_No", typeof(string));
            dt.Columns.Add("PatientName", typeof(string));
            dt.Columns.Add("SEX", typeof(string));
            dt.Columns.Add("PatientAge", typeof(string));
            dt.Columns.Add("PatientID", typeof(string));
            dt.Columns.Add("IN_DATE", typeof(string));
            dt.Columns.Add("InTime", typeof(string));

            dt.Columns.Add("Date", typeof(string));//日期
            dt.Columns.Add("Time", typeof(string));//时间
            dt.Columns.Add("temperature", typeof(string));//体温
            dt.Columns.Add("pulse", typeof(string));//脉搏
            dt.Columns.Add("HeartRate", typeof(string));//心率
            dt.Columns.Add("breathing", typeof(string));//呼吸
            dt.Columns.Add("xueya", typeof(string));//血压
            dt.Columns.Add("Spo2", typeof(string));//血氧饱和度
            dt.Columns.Add("StandUp", typeof(string));//翻身
            dt.Columns.Add("CVP", typeof(string));//CVP
            dt.Columns.Add("Intakename", typeof(string));//输入名称
            dt.Columns.Add("Intakevalue", typeof(string));//输入量
            dt.Columns.Add("Intakediway", typeof(string));//途径
            dt.Columns.Add("Dischargename", typeof(string));//排除名称
            dt.Columns.Add("Dischargevalue", typeof(string));//排除量
            dt.Columns.Add("Tendcontent", typeof(string));//病情及护理措施

            dt.Columns.Add("NursName", typeof(string));//签名
            //dt.Columns.Add("ElectricSignBase64", typeof(string));//电签

            dt.Columns.Add("IsNewPageFlag", typeof(string));//另起一页
            dt.Columns.Add("Group12", typeof(string));//分组统计标识12
            dt.Columns.Add("Group24", typeof(string));//分组统计标识24
            dt.Columns.Add("Vaule01", typeof(string));//合计入量
            dt.Columns.Add("Vaule02", typeof(string));//合计出量
            dt.Columns.Add("DateSum", typeof(string));//统计行显示日期
            dt.Columns.Add("HoursDiy", typeof(string));//自定义统计的小时数-入
            dt.Columns.Add("HoursDiyOut", typeof(string));//自定义统计的小时数-出
            dt.Columns.Add("TimeDiy", typeof(string));//自定义统计的小时数后的时间相对于7:00
            dt.Columns.Add("Groupdiy", typeof(string));//组标识
            dt.Columns.Add("ValueDiy01", typeof(string));//合计入量diy
            dt.Columns.Add("ValueDiy02", typeof(string));//合计出量diy
        }


        private void Form1_Load(object sender, EventArgs e)
        {
            //<<----------自定义工具栏
            //首先清除所有按钮
            axGRPrintViewer1.ResetToolbarContent();

            //逐个按顺序加入需要显示的按钮或控件，

            //打印
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctPrint);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctPageSetup);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctPrinterSetup);

            //浏览
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctSep); //加一个分隔条
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctFirstPage);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctPriorPage);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctNextPage);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctLastPage);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctCurPageNo);

            //显示比例
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctSep); //加一个分隔条
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctZoomIn);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctZoomOut);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctZoomPercent);

            //查看模式
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctSep); //加一个分隔条
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctContinuousPage);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctSinglePage);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctMultiPage);

            //导出
            //这里不显示导出按钮与保存Grid++Report文档按钮
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctSep); //加一个分隔条
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctExportXLSBtn);
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctExportPDFBtn);

            //关闭
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctSep); //加一个分隔条
            axGRPrintViewer1.AddToolbarControl(GRToolControlType.grtctClose);

            //最后调用 UpdateToolbar 更新打印显示控件的工具栏
            axGRPrintViewer1.UpdateToolbar();
            //>>----------自定义工具栏

            axGRPrintViewer1.Start();
        }

        private void SetBlankHeight()
        {
            string sql = @"if(EXISTS (SELECT Id FROM NursingContinuePrint(NOLOCK) WHERE PatientId = '{0}' AND VisitId = '{1}' AND FormId='{3}'))
                                        BEGIN UPDATE NursingContinuePrint SET  BlackHeight ='{4}' WHERE PatientId = '{0}' AND VisitId = '{1}' AND FormId='{3}' END ELSE BEGIN" +
                            " INSERT INTO NursingContinuePrint (PatientId,VisitId,PatientName,FormId,BlackHeight,PageNum)" +
                            " VALUES('{0}','{1}','{2}' ,'{3}','{4}',NULL) END";
            sql = string.Format(sql, this.Patient[0], this.Patient[1], this.Patient[2], (int)FormType.TempbedNursingCVP, Convert.ToString(PageBlankHeight));
            SqlHelper.ExecuteNonQuery(CommandType.Text, sql);
        }

        private void NursingPrint_FormClosing(object sender, FormClosingEventArgs e)
        {
            string printdefaultsql = @"SELECT [PrinterName] FROM [BNNursingDocsSystem_Develop].[dbo].[PrintDefault](NOLOCK) where FromName  = '" + Kind.getFileName() + "' and MACAddress = '" + Kind.GetMacAddress() + "'";
            object printer = SqlHelper.ExecuteScalar(CommandType.Text, printdefaultsql);
            if (printer == null)  //没设置过打印机 - insert 打印机设置！
            {
                printdefaultsql = @"insert into [BNNursingDocsSystem_Develop].[dbo].[PrintDefault] (FromName,MACAddress,PrinterName) values ('" + Kind.getFileName() + "','" + Kind.GetMacAddress() + "','" + Report.Printer.PrinterName + "')";
                SqlHelper.ExecuteNonQuery(CommandType.Text, printdefaultsql);
            }
            else  //设置过
            {
                if (printer.ToString() != Report.Printer.PrinterName)  //打印机不变
                {
                    printdefaultsql = @"update [BNNursingDocsSystem_Develop].[dbo].[PrintDefault] set  PrinterName ='" + Report.Printer.PrinterName + "' where FromName ='" + Kind.getFileName() + "' and MACAddress ='" + Kind.GetMacAddress() + "'  ";
                    SqlHelper.ExecuteNonQuery(CommandType.Text, printdefaultsql);
                }
            }
        }
    }
}